const bannerDb = require("../sequelize/banner");
const { uploadImage } = require("../utils/index");

class BasicService {
	async list(req, res) {
		try {
			return {
				code: 200,
				message: "ok",
				result: await bannerDb.findAll(),
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}
	async add(req, res) {
		try {
			await bannerDb.create(req.body);
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async upload(req, res) {
		try {
			const imgName = await uploadImage(req);
			await bannerDb.create({ url: imgName });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async update(req, res) {
		try {
			await bannerDb.update(req.body, { where: { id: req.body.id } });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}

	async del(req, res) {
		try {
			await bannerDb.destroy({ where: { id: req.body.id } });
			return {
				code: 200,
				message: "ok",
				result: {},
			};
		} catch (err) {
			console.error(err);
			throw new Error(err);
		}
	}
}

module.exports = new BasicService();
